import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:yt_devops/components/log_utils.dart';
import 'package:yt_devops/log_record/student.dart';

import 'add_student_page.dart';
import 'db_manager.dart';

/**
 * 
 * @Description TODO
 * @Author liuer
 * @CreateTime 2023年11月21日 19:44
 */
class SqlitePage extends StatefulWidget {
  const SqlitePage({Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _SqlitePageState();
  }
}

class _SqlitePageState extends State<SqlitePage> {
  List<Student>? _studentList;

  loadAllData() async {
    // _studentList = await DBManager().findAll();
    setState(() {});
  }

  loadData() async {
    _studentList = await DBManager().find(1);
    setState(() {});
  }

  updateData(Student student) async {
    // var count = await DBManager().update(student);
    // if (count > 0) {
    //   // showSnackBar(context, "修改成功");
    //   print("修改成功");
    // } else {
    //   // showSnackBar(context, "修改失败");
    //   print("修改失败");
    // }
  }

  deleteData(int id) async {
    var count = await DBManager().delete(id);
    if (count > 0) {
      print("删除成功");
    } else {
      print("删除失败");
    }
  }

  deleteAllData() async {
    var count = await DBManager().deleteAll();
    if (count > 0) {
      print("删除成功");
    } else {
      print("删除失败");
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("SQLite"),
        actions: [
          IconButton(
            icon: const Icon(Icons.add),
            onPressed: () async {
              // var age = null;
              // int.parse(age);
              var result = await DBManager().findAll();
              if(result != null && result.isNotEmpty){
                var map = result.first;
                ///需要把map进行深拷贝,不然操作的是sqlite里面的数据了,sqlite里面只能读不能直接更新.会报错
                var updateMap = json.decode(json.encode(map));
                updateMap['isUpload'] = true;
                Log.d('updateMap===' + updateMap.toString());
                var result1 =  await DBManager().update(updateMap);
                if (result1 > 0) {
                  Log.d('更新数据成功，result:$result');
                } else {
                  Log.d('更新数据成功，result:$result');
                }
              }
              Navigator.push(context, MaterialPageRoute(builder: (context) {
                return const AddStudentPage();
              }));
            },
          )
        ],
      ),
      body: SingleChildScrollView(
        child: Center(
          child: Column(
            children: [
              ElevatedButton(
                onPressed: () {
                  loadAllData();
                },
                child: const Text("查询所有数据"),
              ),
              ElevatedButton(
                onPressed: () {
                  loadData();
                },
                child: const Text("条件查询"),
              ),
              ElevatedButton(
                onPressed: () {
                  deleteAllData();
                },
                child: const Text("删除全部"),
              ),
              Padding(
                padding: const EdgeInsets.all(10),
                child: _buildTable(),
              ),
            ],
          ),
        ),
      ),
    );
  }

  _buildTable() {
    return Table(
      border: TableBorder.all(),
      defaultVerticalAlignment: TableCellVerticalAlignment.middle,
      children: [
        const TableRow(children: [
          TableCell(child: Text("id")),
          TableCell(child: Text("姓名")),
          TableCell(child: Text("年龄")),
          TableCell(child: Text("性别")),
          TableCell(child: Text("修改")),
          TableCell(child: Text("删除")),
        ]),
        ...?_studentList
            ?.map((e) => TableRow(children: [
          TableCell(child: Text("${e.id}")),
          TableCell(child: Text(e.name)),
          TableCell(child: Text("${e.age}")),
          TableCell(child: Text("${e.sex}")),
          TableCell(
            child: TextButton(
              onPressed: () {
                updateData(e);
              },
              child: const Text("修改"),
            ),
          ),
          TableCell(
            child: TextButton(
              onPressed: () {
                deleteData(e.id!);
              },
              child: const Text("删除"),
            ),
          ),
        ]))
            .toList(),
      ],
    );
  }
}
